/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { cloud, CloudDBCollection, CloudDBZoneQuery } from '@hw-agconnect/cloud-server';
import { userinfo as Userinfo } from './model/userinfo';
import { UserinfoResp } from './model/UserinfoResp'

const ZONE_NAME = 'GuWenDian';

export class DatabaseHelper {
  logger;
  colUserinfo: CloudDBCollection<Userinfo>;

  constructor(logger) {
    this.logger = logger;
    this.colUserinfo = cloud.database({ zoneName: ZONE_NAME }).collection(Userinfo);
  }

  async queryUserinfo(id: string): Promise<UserinfoResp[]> {
    const resList: UserinfoResp[] = [];
    try {
      // Query the user favorites list.
      const userinfoQuery: CloudDBZoneQuery<Userinfo> =
        this.colUserinfo.query().equalTo('id', id);
      const collectData: Userinfo[] = await userinfoQuery.get();
      this.logger.info(`[collect] collectQuery success collectData=>', ${JSON.stringify(collectData)}`);
      if (collectData.length <= 0) {
        return resList;
      }
      for (let i = 0; i < collectData.length; i++) {
        resList.push(new UserinfoResp(
          collectData[i].getId(),
          collectData[i].getNickName(),
          collectData[i].getBirthday(),
          collectData[i].getGender()
        ))
      }
      return resList;
    } catch (error) {
      this.logger.error(`[collect] query resource error ${error}`);
    }
  }
}